/**
 * 09/dic/2011 - fabio.melillo@gmail.com
 */
package demo.unisannio;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;

import org.unisannio.remote.RemoteContentProvider;
import org.unisannio.util.Converter;
import org.unisannio.util.MovieMetaData;
import org.unisannio.util.ServiceInfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

/**
 * @author fabio
 *
 */
public class ContentActivity extends Activity {
	public static RemoteContentProvider contentRemote;
	private ArrayList<String> itemsToShow=new ArrayList<String>();
	private ArrayList<String> actionItems=new ArrayList<String>();
	private ArrayAdapter<String> adapter;
	private String serverUri="content://edu.android.MyMovies/movies";
	private Button bSubscribe,bInsert,bGet;
	private Button bPubblish,bRetract,bUnsub;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.content);
		bSubscribe=(Button) findViewById(R.id.buttSubscribe);
		bPubblish=(Button) findViewById(R.id.buttPubblish);
		bInsert=(Button) findViewById(R.id.buttInsert);
		bGet=(Button) findViewById(R.id.buttGet);
		bRetract=(Button) findViewById(R.id.buttRetract);
		bUnsub=(Button) findViewById(R.id.buttUnSubscribe);
		this.populateItems();
		String[] items=new String[itemsToShow.size()];
		items=itemsToShow.toArray(items);
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, items);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		Spinner actions = (Spinner) findViewById(R.id.spinnerAction);
		actions.setAdapter(adapter);
		bSubscribe.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				if(contentRemote!=null){
				
					Spinner actions = (Spinner) findViewById(R.id.spinnerAction);

					Uri uri = Uri.parse(actionItems.get(actions
							.getSelectedItemPosition()));
					ServiceInfo sinfo=new ServiceInfo();
					sinfo.addDescriptor(uri.toString(), "movies", MovieMetaData.MOVIE_SCHEMA, ServiceInfo.CONTENT_PROVIDER);
					contentRemote.sendToSuperPeer(sinfo, Converter.SUBSCRIBE);

				}
				
				else{
					AlertDialog.Builder builder = new AlertDialog.Builder(
							ContentActivity.this);
					builder.setMessage("Registrati per poter effettuare una richiesta remota\n");
					builder.setCancelable(false);
					builder.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();
				}
			}
		});
		
		bPubblish.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(contentRemote!=null){
					Spinner actions = (Spinner) findViewById(R.id.spinnerAction);

					Uri uri = Uri.parse(actionItems.get(actions
							.getSelectedItemPosition()));
					ServiceInfo sinfo=new ServiceInfo();
					sinfo.addDescriptor(uri.toString(), "movies", MovieMetaData.MOVIE_SCHEMA, ServiceInfo.CONTENT_PROVIDER);
					contentRemote.sendToSuperPeer(sinfo, Converter.PUBLISH);
				}
				else{
					AlertDialog.Builder builder = new AlertDialog.Builder(
							ContentActivity.this);
					builder.setMessage("Registrati per poter effettuare una richiesta remota\n");
					builder.setCancelable(false);
					builder.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();
				}
			}
		});
		
		
		bUnsub.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(contentRemote!=null){
					Spinner actions = (Spinner) findViewById(R.id.spinnerAction);

					Uri uri = Uri.parse(actionItems.get(actions
							.getSelectedItemPosition()));
					ServiceInfo sinfo=new ServiceInfo();
					sinfo.addDescriptor(uri.toString(), "movies", MovieMetaData.MOVIE_SCHEMA, ServiceInfo.CONTENT_PROVIDER);
					contentRemote.sendToSuperPeer(sinfo, Converter.UNSUBSCRIBE_FROM_SERVICE);
				}
				else{
					AlertDialog.Builder builder = new AlertDialog.Builder(
							ContentActivity.this);
					builder.setMessage("Registrati per poter effettuare una richiesta remota\n");
					builder.setCancelable(false);
					builder.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();
				}
			}
		});
		
		bRetract.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(contentRemote!=null){
					Spinner actions = (Spinner) findViewById(R.id.spinnerAction);

					Uri uri = Uri.parse(actionItems.get(actions
							.getSelectedItemPosition()));
					ServiceInfo sinfo=new ServiceInfo();
					sinfo.addDescriptor(uri.toString(), "movies", MovieMetaData.MOVIE_SCHEMA, ServiceInfo.CONTENT_PROVIDER);
					contentRemote.sendToSuperPeer(sinfo, Converter.RETRACT_FROM_SERVICE);
				}
				else{
					AlertDialog.Builder builder = new AlertDialog.Builder(
							ContentActivity.this);
					builder.setMessage("Registrati per poter effettuare una richiesta remota\n");
					builder.setCancelable(false);
					builder.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();
				}
			}
		});
		
		bInsert.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(contentRemote!=null){
					add();
				}
				
				else{
					AlertDialog.Builder builder = new AlertDialog.Builder(
							ContentActivity.this);
					builder.setMessage("Registrati per poter effettuare una richiesta remota\n");
					builder.setCancelable(false);
					builder.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();
				}
			}

			
		});
		bGet.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(contentRemote!=null){
					get();
				}
				else{
					AlertDialog.Builder builder = new AlertDialog.Builder(
							ContentActivity.this);
					builder.setMessage("Registrati per poter effettuare una richiesta remota\n");
					builder.setCancelable(false);
					builder.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();
				}
			}

			
		});
	}
	private void get() {
		// TODO Auto-generated method stub
		LayoutInflater inflater=LayoutInflater.from(this);
		View addView = inflater.inflate(R.layout.get, null);
		final DialogWrapper wrapper = new DialogWrapper(addView);
		new AlertDialog.Builder(this)
				.setTitle("Insert Title")
				.setView(addView)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						processGet(wrapper);
					}

				})
		.setNegativeButton("Cancel",
												new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,
														int whichButton) {
				// ignore, just dismiss
			}
		})
		.show();
	}
	
	private void add() {
		LayoutInflater inflater=LayoutInflater.from(this);
		View addView=inflater.inflate(R.layout.add_edit, null);
		final DialogWrapper wrapper=new DialogWrapper(addView);
		
		new AlertDialog.Builder(this)
				.setTitle("Insert")
				.setView(addView)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						processAdd(wrapper);
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								// ignore, just dismiss
							}
						}).show();
	}
		
	private void processAdd(DialogWrapper wrapper) {
		if (contentRemote.isChosenAddress()){
		ContentValues cv=new ContentValues();
		cv.put(MovieMetaData.MOVIE_TITLE_KEY, wrapper.getTitle());
		cv.put(MovieMetaData.MOVIE_DIRECTOR_KEY, wrapper.getRegista());
		cv.put(MovieMetaData.MOVIE_YEAR_KEY, wrapper.getAnno());
		
			new InsertMoviesTask(ContentActivity.this,cv).execute(contentRemote);
		}
		else {
			AlertDialog.Builder builder = new AlertDialog.Builder(ContentActivity.this);
			builder.setMessage("Selezionare prima un indirizzo.\nMenu->Indirizzi");
			builder.setCancelable(false);
			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			               dialog.cancel();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
		}
		
	}
	
	private void processGet(DialogWrapper wrapper) {
		if (contentRemote.isChosenAddress()){
			String title=wrapper.getTitle();
			new GetMoviesTask(ContentActivity.this, title).execute(contentRemote);
			}
			else {
				AlertDialog.Builder builder = new AlertDialog.Builder(ContentActivity.this);
				builder.setMessage("Selezionare prima un indirizzo.\nMenu->Indirizzi");
				builder.setCancelable(false);
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				               dialog.cancel();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
			}
		
	}
	private void populateItems() {
		//popolo in qualche modo il mio spinnerino [soluzione brutta]
		//sarebbe meglio creare un oggetto MyData, dove new MyData(key,"value")
		itemsToShow.add("Movies");
		actionItems.add(serverUri);
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result =super.onCreateOptionsMenu(menu);
		MenuItem indirizzi=menu.add(Menu.NONE,1,1,"Indirizzi");
		indirizzi.setIcon(android.R.drawable.ic_menu_agenda);
		MenuItem config=menu.add(Menu.NONE,2,2,"Configurazione");
		config.setIcon(android.R.drawable.ic_menu_manage);
		return result;
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		setResult(RESULT_OK,null);
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case 1:
			if (ContentActivity.contentRemote!=null){
				Intent intent=new Intent(this, AddressListActivity.class);
				startActivityForResult(intent,1);
				break;
			}else {
			AlertDialog.Builder builder = new AlertDialog.Builder(ContentActivity.this);
			builder.setMessage("Configura prima il Peer");
			builder.setCancelable(false);
			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			               dialog.cancel();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
			}
			break;
			
		case 2:
			Intent intent=new Intent(this, ConfigActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data!=null) {
		Bundle extras=data.getExtras();
		String peerAddress=extras.getString("peerAddress");
		ArrayList<Address> destinationList=new ArrayList<Address>();
		destinationList.add(new Address(peerAddress));
		contentRemote.saveChosenAddress(destinationList);
//		otherPeerAddress.setText("peer selezionato: "+peerAddress);
		}
		else{
//			otherPeerAddress.setText("nessun peer selezionato");
		}
	}

	
	
	class DialogWrapper {
		EditText titleField=null;
		EditText registaField=null;
		EditText annoField=null;
		View base=null;
		
		DialogWrapper(View base) {
			this.base=base;
			registaField=(EditText)base.findViewById(R.id.regista);
		}
		
		String getTitle() {
			return(getTitleField().getText().toString());
		}
		
		String getRegista() {
			return((getRegistaField().getText().toString()));
		}
		String getAnno(){
			return((getAnnoField().getText().toString()));
		}
		
		private EditText getAnnoField() {
			if (annoField==null) {
				annoField=(EditText)base.findViewById(R.id.anno);
			}
			
			return(annoField);
		
		}

		private EditText getTitleField() {
			if (titleField==null) {
				titleField=(EditText)base.findViewById(R.id.title);
			}
			
			return(titleField);
		}
		
		private EditText getRegistaField() {
			if (registaField==null) {
				registaField=(EditText)base.findViewById(R.id.regista);
			}
			
			return(registaField);
		}
	}
}
